package com.loong.common.mvc.filter;


import com.loong.common.utils.UUIDUtils;
import com.loong.common.utils.UserIdUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
@Component
@WebFilter(urlPatterns = "/*", filterName = "requestLogTraceFilter")
public class Filter1_RequestLogTraceFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uid = request.getHeader("uid");
        String uuid = UUIDUtils.getUUID();
        String traceId = StringUtils.isEmpty(uid) ? uuid : uid + "-" + uuid;
        MDC.put("traceId", traceId);
        if(!StringUtils.isEmpty(uid)){
           try {
               UserIdUtils.setUserId(Integer.parseInt(uid));
               // 可以转换int成功的参数，才传递
               MDC.put("uid", uid);
               // 每次先初始化需要情况job脱敏权限
           }catch (Exception e){
              log.error("前端传参uid错误：{} exception:{}",uid,e);
           }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }

}
